/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.braveo.dict.business;

import com.braveo.common.config.BraveConfigParseException;
import com.braveo.dict.business.annotation.ConfigItem;
import com.braveo.dict.db.BraveDictEntryDaoManager;
import com.braveo.tools.config.ConfigManager;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 *
 * @author jeff.huang
 */
public class CreatorApplication {
    private static final CreatorApplication app = new CreatorApplication();

    private ConfigManager cm = ConfigManager.getInstance();

    private BraveDictEntryDaoManager daoManager;

    private CreatorApplication(){
        init();
    }

    public static CreatorApplication getApplication(){
        return app;
    }

    public void init(){
        daoManager = BraveDictEntryDaoManager.getManager();
        daoManager.setDaoName("jaxb");
    }

    public BraveDictEntryDaoManager getDaoManager() {
        return daoManager;
    }

    public CreatorConfig getConfig(){
        CreatorConfig cc = new CreatorConfig();

        try{
            Field[] fs = cc.getClass().getDeclaredFields();
            for(Field f : fs){
                String configName = f.getName();
                ConfigItem ci = f.getAnnotation(ConfigItem.class);
                if(ci != null && ci.value().length() > 0)
                    configName = ci.value();

                String value = cm.getConfig(configName);
                if(value != null){
                    PropertyDescriptor pd = new PropertyDescriptor(f.getName(), cc.getClass());
                    Method m = pd.getWriteMethod();
                    m.invoke(cc, value);
                }

            }
        }catch(Exception e){
            throw new BraveConfigParseException(e);
        }

        return cc;
    }

    public void setConfig(CreatorConfig cc){
        if(cc == null)
            return;

        try{
            Field[] fs = cc.getClass().getDeclaredFields();
            for(Field f : fs){
                String configName = f.getName();
                ConfigItem ci = f.getAnnotation(ConfigItem.class);
                if(ci!=null && ci.value().length()>0)
                    configName = ci.value();

                String value = "";
                PropertyDescriptor pd = new PropertyDescriptor(f.getName(), cc.getClass());
                Method m = pd.getReadMethod();
                Object o = m.invoke(cc);
                if(o == null){
                    continue;
                }else{
                    value = o.toString();
                }
                cm.setConfig(configName, value);
            }
        }catch(Exception e){
            throw new BraveConfigParseException(e);
        }
    }
}
